import { InputManager } from './currency.manager';
import { CurrencyPipe } from '@angular/common';

export class InputService {
  //
  private inputManager: InputManager;

  constructor(private currencyPipe: CurrencyPipe, private htmlInputElement: any, private options: any) {
    this.inputManager = new InputManager(htmlInputElement);
  }

  get rawValue(): string {
    return this.inputManager.rawValue;
  }

  set rawValue(value: string) {
    this.inputManager.rawValue = value;
  }

  get value(): number {
    return this.clearMask(true, this.rawValue);
  }

  set value(value) {
    this.rawValue = this.applyMask(true, '' + value);
  }

  updateOptions(options: any): void {
    const value: number = this.value;
    this.options = options;
    this.value = value;
  }

  formatNumber(v) {
    this.rawValue = this.clearMask(false, v);
  }

  addNumber(isNumber: boolean, keyCode: any): void {
    if (!this.rawValue) {
      this.rawValue = '';
    }
    this.rawValue = this.applyMask(isNumber, keyCode);
  }

  applyMask(isNumber: boolean, rawValue: string): string {
    const onlyNumbers = this.clearMask(false, rawValue);
    if (!onlyNumbers) {
      return '';
    }
    if (isNumber) {
      return onlyNumbers;
    }

    const { currencyCode } = this.options;
    return this.currencyPipe.transform(onlyNumbers, currencyCode, true);
  }

  clearMask(isNumber: boolean, rawValue: string): any {
    if ([null, 'null', '', undefined, 'undefined', NaN, 'NaN'].includes(rawValue)) {
      return isNumber ? 0 : '';
    }
    const { decimal, precision, prefix, thousands } = this.options;
    let value = rawValue.replace(prefix, '');
    value = value.replace(new RegExp('\\' + thousands, 'g'), '');
    value = value.replace(new RegExp(`[^0-9${decimal}]`, 'g'), '');
    const v = parseFloat(value);

    if (isNumber) {
      return isNaN(v) || v === 0 ? 0 : v;
    }
    return isNaN(v) || v === 0 ? '' : v.toFixed(precision);
  }
}
